package com.banshuibao.bsb_android.activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;

import com.banshuibao.bsb_android.Constants;
import com.banshuibao.bsb_android.R;
import com.banshuibao.bsb_android.adapter.SearchAdapter;
import com.banshuibao.bsb_android.http.HttpResponse;
import com.banshuibao.bsb_android.http.HttpUtil;
import com.banshuibao.bsb_android.model.ExpertResultModel;
import com.banshuibao.bsb_android.model.MediaModel;
import com.banshuibao.bsb_android.model.SearchRequestModel;
import com.banshuibao.bsb_android.model.SearchResultModel;
import com.banshuibao.bsb_android.pulltolistview.PullToRefreshBase;
import com.banshuibao.bsb_android.pulltolistview.PullToRefreshListView;
import com.banshuibao.bsb_android.util.IntentManager;
import com.banshuibao.bsb_android.util.XToast;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.List;

public class SearchActivity extends BaseActivity implements PullToRefreshListView.OnRefreshListener2, View.OnClickListener, TextWatcher, AdapterView.OnItemClickListener {

    private PullToRefreshListView ptrlv;
    private ListView listView;
    private int startId, endId;
    private Spinner spinner;
    private TextView search;
    private EditText content_et;
    private SearchAdapter searchAdapter;
    private String[] goods = new String[]{"专家答疑", "大咖访谈", "财税课堂", "考前辅导", "政策解读"};//0 政策解读 1微课堂2考前辅导 3 大咖访谈 4 专家答疑
    private String[] goods_id = new String[]{"4", "3", "1", "2", "0"};
    private int index = 0;
    private boolean isUp;
    private TextView msg;
    private int rows;
    private SearchResultModel.DataBean dataBean;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search);
        initView();
        initSpinner();
    }

    public void initView() {
        spinner = findViewById(R.id.spinner);
        search = findViewById(R.id.menu);
        search.setOnClickListener(this);
        content_et = findViewById(R.id.et);
        msg = findViewById(R.id.msg);
        content_et.addTextChangedListener(this);
        ptrlv = findViewById(R.id.ptrlv);
        ptrlv.setMode(PullToRefreshBase.Mode.PULL_FROM_END);
        ptrlv.setOnRefreshListener(this);
        listView = ptrlv.getRefreshableView();
        listView.setDivider(null);
        searchAdapter = new SearchAdapter(this);
        listView.setAdapter(searchAdapter);
        listView.setOnItemClickListener(this);
    }

    public void initSpinner() {
        ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, R.layout.spinner_text_style, goods);
        arrayAdapter.setDropDownViewResource(android.R.layout.simple_list_item_single_choice);
        spinner.setAdapter(arrayAdapter);
        spinner.setSelection(index, true);
        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                //  XToast.showToast(SearchActivity.this, goods[i]);
                index = i;
                searchAdapter.clearAdapter();//清空搜索结果
                content_et.setText("");//清空输入值
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {
            }
        });
    }

    public void getData() {
        isUp = false;
        startId = 1;
        endId = startId + 4;
        if (searchAdapter != null) {
            int count = searchAdapter.getCount();
            if (count >= 10) {
                endId += count - 5;
            }
        }
        requestNet();
    }

    @Override
    public void onPullDownToRefresh(PullToRefreshBase refreshView) {
        getData();
    }

    @Override
    public void onPullUpToRefresh(PullToRefreshBase refreshView) {
        isUp = true;
        endId = startId + 4;
        requestNet();
    }

    /**
     * 请求网络获取数据
     */
    public void requestNet() {
        final String content = content_et.getText().toString().trim();
        if (TextUtils.isEmpty(content)) {
            XToast.showToast(this, "请输入搜索内容！");
            if (ptrlv != null) {
                ptrlv.onRefreshComplete();
            }
            return;
        }
        showProgressDialog();
        SearchRequestModel requestModel = new SearchRequestModel();
        requestModel.setSinceId(startId);
        requestModel.setMaxId(endId);
        requestModel.setContent(content);
        requestModel.setType(goods_id[index]);
        HttpUtil.doPost(Constants.Url.HOME_SEARCH, requestModel, new HttpResponse(this, SearchResultModel.class) {
            @Override
            public void onResult(Object obj) {
                SearchResultModel searchResultModel = (SearchResultModel) obj;
                rows = searchResultModel.getRows();
                List<SearchResultModel.DataBean> data = searchResultModel.getData();
                startId += rows;
                searchAdapter.setKey(content);//设置关键字
                if (isUp) {
                    searchAdapter.upData(data);
                } else {
                    searchAdapter.downData(data);
                }
                if (searchAdapter != null && searchAdapter.getCount() == 0) {
                    ptrlv.setVisibility(View.GONE);
                    msg.setVisibility(View.VISIBLE);
                } else {
                    ptrlv.setVisibility(View.VISIBLE);
                    msg.setVisibility(View.GONE);
                }
            }

            @Override
            public void responseEnd() {
                super.responseEnd();
                ptrlv.onRefreshComplete();
                cancelProgressDialog();
            }
        });

    }


    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.menu:
                getData();
                break;
        }
    }

    /**
     * 输入内容变更
     * 内容为空列表清空
     *
     * @param charSequence
     * @param i
     * @param i1
     * @param i2
     */
    @Override
    public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

    }

    @Override
    public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
        if (charSequence.length() == 0) {
            searchAdapter.clearAdapter();
        }
    }

    @Override
    public void afterTextChanged(Editable editable) {

    }

    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
        String name = goods[index];
        dataBean = searchAdapter.getItem(i - 1);

        if ("专家答疑".equals(name)) {
            ExpertResultModel.DataBean bean = new ExpertResultModel.DataBean();
            bean.setUuid(dataBean.getUuid());
            bean.setAskPrice(dataBean.getAskPrice());
            bean.setApproveNum(dataBean.getApproveNum());
            bean.setQuestion(dataBean.getTitle());
            bean.setCreateDate(dataBean.getCreateDate());
            bean.setHeadImg(dataBean.getHeadImg());
            bean.setName(dataBean.getName());
            bean.setPositiotn(dataBean.getPositiotn());
            bean.setQuPrice(dataBean.getQuPrice());
            IntentManager.goExpertDetailActivity(SearchActivity.this, bean.getUuid());
        } else if ("大咖访谈".equals(name)) {
            buyMedia(dataBean);
        } else if ("考前辅导".equals(name)) {
            buyMedia(dataBean);
        } else if ("财税课堂".equals(name)) {
            buyMedia(dataBean);
        } else if ("政策解读".equals(name)) {
            IntentManager.goCoachPolicyDetailActivity(SearchActivity.this, dataBean.getUuid(), dataBean.getTitle(), 0);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (searchAdapter != null) {
            searchAdapter.clearAdapter();
            searchAdapter = null;
        }
    }

    void buyMedia(final SearchResultModel.DataBean dataBean) {
        MediaModel.BuyBody buyBody = new MediaModel.BuyBody();
        buyBody.setUuid(dataBean.getUuid());
        HttpUtil.doPost(Constants.Url.IS_BUY, buyBody, new HttpResponse(this) {
            @Override
            public void onResult(Object obj) {
                JSONObject jsonObject = null;
                JSONObject jsonObject1 = null;
                try {
                    jsonObject = new JSONObject((String) obj);
                    jsonObject1 = jsonObject.getJSONObject("data");
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                if (jsonObject1 != null) {
                    String type = jsonObject1.optString("type");
                    String vid = jsonObject1.optString("vid");
                 /* *//*  if ("0".equals(type) && !TextUtils.isEmpty(vid)) {
                        IntentManager.goMediaPlayActivity(context, vid);
                    } else if (TextUtils.equals("2", type)) {
                        IntentManager.goCheckInActivity(context);*//*
                    } else {
                        new AlertDialog.Builder(context).
                                setMessage("购买365会员可以免费观看所有视频,或者支付" + dataBean.getVideoPrice() + "元购买本集").
                                setPositiveButton("购买", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialogInterface, int i) {
                                        IntentManager.goPayResultActivity((Activity) context, dataBean.getTitle(), String.valueOf(dataBean.getVideoPrice()), dataBean.getUuid(), 4);
                                    }
                                }).setNegativeButton("取消", null).create().show();
                    }*/
                }
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case 200:
                    if (dataBean != null)
                        buyMedia(dataBean);
                    break;
            }
        }
    }
}
